<template>

  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">Home</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <el-card class="box-card">
    <el-row :gutter="15">
      <el-col :span="8">
        <el-input
            v-model="user_data.queryName"
            style="max-width: 600px"
            placeholder="搜索用户"
            class="input-with-select"
        >
          <template #append>
            <el-button :icon="Search" @click="searchUser"/>
          </template>
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" :icon="Plus" @click="addDialogVisible=true">增加用户</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table :data="user_data.tableData" stripe class="table">
        <el-table-column prop="id" label="id" width="50"/>
        <el-table-column prop="name" label="账号" width="80"/>
        <el-table-column prop="nick_name" label="昵称"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="role_name" label="角色"/>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
              Edit
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >
              Delete
            </el-button>
            <el-button
                size="small"
                type="warning"
                @click="handleReset(scope.$index, scope.row)"
            >
              Reset
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-pagination
          v-model:current-page="user_data.pageNum"
          v-model:page-size="user_data.pageSize"
          :page-sizes=page_size
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total=user_data.total
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="foot"
      />
    </el-row>
  </el-card>
  <!--  增加用户对话框-->
  <el-dialog v-model="addDialogVisible" title="增加用户" width="500" :before-close="addFormRest">
    <el-form :model="user_form" :rules="user_rules" ref="addFormRef">
      <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="user_form.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="pwd">
        <el-input v-model="user_form.pwd" autocomplete="off" show-password/>
      </el-form-item>
      <el-form-item label="确认密码" :label-width="formLabelWidth" prop="real_pwd">
        <el-input v-model="user_form.real_pwd" autocomplete="off" show-password/>
      </el-form-item>
      <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick_name">
        <el-input v-model="user_form.nick_name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="user_form.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="user_form.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="角色" :label-width="formLabelWidth">
        <el-select v-model="user_form.role_id" placeholder="请选择角色">
          <el-option :label="r.name" :value="r.id" v-for="r in roles" :key="r.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addFormRest">取消</el-button>
        <el-button type="primary" @click="addUser(addFormRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  编辑用户-->
  <el-dialog v-model="editDialogVisible" title="修改用户" width="500">
    <el-form :model="edit_form"  ref="editFormRef">
      <el-form-item label="用户名" :label-width="formLabelWidth" prop="name">
        <el-input v-model="edit_form.name" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick_name">
        <el-input v-model="edit_form.nick_name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="edit_form.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="edit_form.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="角色" :label-width="formLabelWidth">
        <el-select v-model="edit_form.role_id" placeholder="请选择角色">
          <el-option :label="r.name" :value="r.id" v-for="r in roles" :key="r.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="editUser">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  删除用户-->
  <el-dialog v-model="deleteDialogVisible" title="删除用户" width="500">
    <span>是否确认删除账号：{{remove_user.name }}这个用户吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="deleteUser">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
   <!--  重置密码-->
  <el-dialog v-model="resetDialogVisible" title="删除用户" width="500">
    <span>是否确认重置账号：{{reset_user.name }}这个用户的密码吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="resetUser">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ArrowRight, Search, Plus} from "@element-plus/icons-vue";
import api from '../api/index'
import {onMounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";

const size = ref('default')
const background = ref(false)
const disabled = ref(false)
const addDialogVisible = ref(false)
const formLabelWidth = '80px'
const addFormRef = ref(null)
const editDialogVisible = ref(false)
const editFormRef = ref(null)
let userID = ref(0)
const deleteDialogVisible = ref(false)
const resetDialogVisible = ref(false)
let roles = ref([])

const user_data = reactive({
  tableData: [],
  total: 10,
  pageNum: 1,
  pageSize: 10,
  queryName: '',
})
const user_form = reactive({
  'name': null,
  'pwd': null,
  'real_pwd': null,
  'nick_name': null,
  'phone': null,
  'email': null,
  'role_id':null,
})
let edit_form = reactive({
  'id':null,
  'name': null,
  'nick_name': null,
  'phone': null,
  'email': null,
  'role_id':null,
})
let remove_user = reactive({
  id:null,
  name:null,
  nick_name:null
})
let reset_user = reactive({
  id:null,
  name:null,
  nick_name:null
})

let page_size = ref([1, 2, 5, 10])

//定义验证确认密码的规则
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('确认密码不能为空'))
  } else if (value !== user_form.pwd) {
    callback(new Error("两次密码不匹配"))
  } else {
    callback()
  }
}
//校验用户验证规则
const user_rules = reactive({
  name: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur'}
  ],
  pwd: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在6到20个字符', trigger: 'blur'}
  ],
  real_pwd: [
    {required: true, message: '确认密码不能为空', trigger: 'blur'},
    {validator: validatePass2, trigger: 'blur'}
  ],
  nick_name: [
    {required: true, message: '昵称不能为空', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ]
})

onMounted(() => {
  get_user_list()
  get_role_list()
})
const get_user_list = () => {
  let params = {
    'pnum': user_data.pageNum,
    'psize': user_data.pageSize,
    'name': user_data.queryName,
  }
  api.get_users_list({params}).then(res => {
    //更新用户列表数据
    user_data.tableData = res.data.data.data
    //更新分页列表数据总数
    user_data.total = res.data.data.total
  })
}
const handleSizeChange = (val) => {
  //修改每页显示多少条数据
  user_data.pageSize = val
  get_user_list()
}
const handleCurrentChange = (val) => {
  //修改显示第几页
  user_data.pageNum = val
  get_user_list()
}
const searchUser = () => {
  //初始化页码
  user_data.pageNum = 1
  get_user_list()
}

const addFormRest = () => {
  addFormRef.value.resetFields()
  //关闭对话框
  addDialogVisible.value = false
}

//添加用户
const addUser = (formRef) => {
  formRef.validate((valid) => {
    if (valid) {
      console.log('验证通过')
      api.add_user(user_form).then(res => {
        //根据响应的结果进行处理
        if (res.data.status === 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
          })
          //关闭对话框
          addFormRest()
          //重新获取数据
          get_user_list()
        } else {
          ElMessage({
            message: res.data.msg,
            type: 'warning',
          })
        }
      })
    } else {
      console.log('验证失败')
      return false
    }
  })
}
//编辑用户
const handleEdit = (index, row) => {
  editDialogVisible.value = true
  userID.value = row.id
  //将选中的数据赋值到编辑表单中
  edit_form = row
}

const editUser = (editForm) =>{
  api.edit_user(userID.value,edit_form).then(res =>{
    console.log(res)
      if(res.data.status === 200){
        ElMessage({
          message: res.data.msg,
          type: 'success',
        })
        //关闭对话框
        editDialogVisible.value = false
        //重新获取数据
        get_user_list()
      }else{
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        })
      }
    })
}
//删除用户控制器
const handleDelete = (index,row) =>{
  remove_user.id = row.id
  remove_user.name=row.name
  remove_user.nick_name=row.nick_name
  deleteDialogVisible.value = true
}
//删除用户操作
const deleteUser = () =>{
  //发送删除用户的接口
  api.delete_user(remove_user.id).then(res=> {
    if (res.data.status === 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success',
      })
      deleteDialogVisible.value = false
      get_user_list()
    }else{
      ElMessage({
          message: res.data.msg,
          type: 'warning',
      })
    }
  })
}
//显示重置密码对话框
const handleReset = (index,row) =>{
  resetDialogVisible.value = true
  reset_user.id = row.id
  reset_user.name=row.name
  reset_user.nick_name=row.nick_name
}
//重置用户密码操作
const resetUser = () =>{
  api.reset_user_password(reset_user.id).then(res =>{
    if (res.data.status === 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success',
      })
      resetDialogVisible.value = false
      get_user_list()
    }else{
      ElMessage({
        message: res.data.msg,
        type: 'warning',
      })
    }
  })
}
//获取角色列表
const get_role_list=()=>{
  api.get_roles().then(res=>{
    roles.value=res.data.data
  })
}

</script>

<style scoped>

.box-card {
  margin-top: 20px;
}

.table {
  width: 100%;
  margin-top: 20px;
}

.foot {
  margin-top: 20px;
}
</style>